package com.ttl.bc.report.receive.material;



import hibernate.util.HibernateUtil;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.view.JasperViewer;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.hibernate.Session;

import com.ttl.bc.ap.stkrequest.BCStkRequestDAO;
import com.ttl.common.util.CommonUtils;
import com.ttl.stock.action.YearMonthReport;
import com.ttl.stock.db.ITTL_MonthlyInventoryReport;
import com.ttl.stock.db.StockBO;
import com.ttl.stock.db.StockDAO;
import com.ttl.view.ITTL_MonthlyInventory;
import com.ttl.view.ITTL_OutStock;
import com.ttl.view.VMStockInOut;

public class ReportReceiveMaterialAction extends DispatchAction {

	public ActionForward blank(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
				
		return mapping.findForward("blank");
	}	

	public ActionForward receiveAll(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		Calendar ca1 = Calendar.getInstance();
		// start
		String hql = "select distinct year(docDate), month(docDate) " +
				"from ITTL_OutStock " +
				"where docDate is not null " +
				"order by year(docDate) desc, month(docDate) desc";
		List outList = new StockDAO().find(hql);
		ArrayList<YearMonthReport> yearMonthList3 = new ArrayList<YearMonthReport>();
		
		if(outList!=null && !outList.isEmpty()) {
			for (int i = 0; i < outList.size(); i++) { 		
				Object[] tuple = (Object[])outList.get(i);
				int yearReport = Integer.valueOf(tuple[0].toString());
				int monthReport = Integer.valueOf(tuple[1].toString());
															
				ca1.set(yearReport, monthReport-1,1);
				java.util.Date d = new java.util.Date(ca1.getTimeInMillis());
				
				yearMonthList3.add(new YearMonthReport(""+(yearReport)+"-"+new SimpleDateFormat("MMMM").format(d), 
						""+(yearReport)+"-"+monthReport));									
			}

		}			
		request.setAttribute("yearMonthList3", yearMonthList3);			
		// end
		
		return mapping.findForward("blank_receive_all");
	}

	public ActionForward receiveByDepartment(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
				
		Calendar ca1 = Calendar.getInstance();
		// start
		String hql = "select distinct year(docDate), month(docDate) " +
				"from ITTL_OutStock " +
				"where docDate is not null " +
				"order by year(docDate) desc, month(docDate) desc";
		List outList = new StockDAO().find(hql);
		ArrayList<YearMonthReport> yearMonthList3 = new ArrayList<YearMonthReport>();
		
		if(outList!=null && !outList.isEmpty()) {
			for (int i = 0; i < outList.size(); i++) { 		
				Object[] tuple = (Object[])outList.get(i);
				int yearReport = Integer.valueOf(tuple[0].toString());
				int monthReport = Integer.valueOf(tuple[1].toString());
															
				ca1.set(yearReport, monthReport-1,1);
				java.util.Date d = new java.util.Date(ca1.getTimeInMillis());
				
				yearMonthList3.add(new YearMonthReport(""+(yearReport)+"-"+new SimpleDateFormat("MMMM").format(d), 
						""+(yearReport)+"-"+monthReport));									
			}

		}			
		request.setAttribute("yearMonthList3", yearMonthList3);			
		// end
		
		return mapping.findForward("blank_receive_by_department");
	}	
	
	@SuppressWarnings("unchecked")
	public ActionForward showReceiveAll(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
//		ReportReceiveMaterialBO bo = new ReportReceiveMaterialBO();
//		bo.getReportReceiveAll(form,request,response, "/receiveMaterial.jasper");
		
		ReportReceiveMaterialForm rptForm = (ReportReceiveMaterialForm)form;
		String monthId = rptForm.getMonthId();
		String yearId = rptForm.getYearId();
		String[] selectedItems = rptForm.getSelectedItems();
		String	process = rptForm.getProcess();
		
		String[] yearMonth = rptForm.getYearMonth().split("-");
		yearId = yearMonth[0];
		monthId = yearMonth[1];
		
		String nameOfReport = "";
		String timeToRequestReport = "";
		HashMap hashMap = new HashMap();
		if(process!=null && process.equalsIgnoreCase("new")) {
			Calendar cal = new GregorianCalendar(Integer.parseInt(yearId), Integer.parseInt(monthId)-1, 1);
			int  days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);     // 30  
			System.out.println("days = "+days);
			String sDate = yearId +"-" + monthId +"-1";
			String eDate = yearId +"-" + monthId +"-"+days;			
			System.out.println("sDate="+sDate);
			System.out.println("eDate="+eDate);
			timeToRequestReport = CommonUtils.now(); 
			new StockDAO().getMaterialOutStockReport(sDate, eDate, timeToRequestReport, "10");
			
			
			nameOfReport = "/ireport/receiveMaterial2.jasper";
		}else {
			nameOfReport = "/ireport/receiveMaterial21.jasper";
			nameOfReport = "/ireport/receiveMaterial24.jasper";
		}
		System.out.println("nameOfReport = "+nameOfReport);
		
		String dept = "";
		for(int i=0; i<selectedItems.length; i++) {
			dept = dept + "'"+selectedItems[i] +"',";
		}
		dept = " in ("+ dept.substring(0, dept.length()-1)+ ")";
		
		
		String monthStr[] = { "January","February", "March", "April", "May", "June", 
							  "July","August", "September", "October", "November", "December"};
		
		 
 		hashMap.put("monthId", monthId);
		System.out.println("monthId = "+monthId);
		hashMap.put("yearId", yearId);
		System.out.println("yearId = "+yearId);
		hashMap.put("dept", dept);
		System.out.println("dept = "+dept);
		hashMap.put("monthStr", monthStr[Integer.parseInt(monthId)-1]);
		System.out.println("monthStr = "+monthStr);
		hashMap.put("timeToRequestReport", timeToRequestReport);
		System.out.println("timeToRequestReport = "+timeToRequestReport);
		
		if(CommonUtils.runReportToPdf(response, getServlet(), hashMap, nameOfReport)==true) {
			System.out.println("run report to pdf: complete");
		}else {
			System.out.println("run Report to pdf: can't run report");
		}		
//		Connection connection;
//		ServletOutputStream servletOutputStream = response.getOutputStream();
//		
//		InputStream reportStream = getServlet().getServletConfig()
//						.getServletContext().getResourceAsStream("/ireport/receiveMaterial.jasper");
//
//		
//		response.setContentType("application/pdf");
//		//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//		Class.forName("net.sourceforge.jtds.jdbc.Driver");		
////		connection = DriverManager.getConnection("jdbc:odbc:ttl51","sa","admin123");
//		connection = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.1.2:1433/ttl51;user=sa;password=admin@123");
//		
//		JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, hashMap, connection);
//		connection.close();
//		servletOutputStream.flush();
//		servletOutputStream.close();		
		
		return null;//mapping.getInputForward();
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
	public ActionForward showReceiveByDepartment(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		try {
			ReportReceiveMaterialBO bo = new ReportReceiveMaterialBO();
			bo.getReportReceiveAll(form,request,response, "/receiveMaterial.jasper");
			ArrayList<ITTL_OutStock> al = bo.getReceiveByDepartment(form,request,response, "/receiveMaterial.jasper");
			
			ArrayList<ITTL_OutStock> al2 = new ArrayList<ITTL_OutStock>();
			
			if(!al.isEmpty()) {
				for (ITTL_OutStock ittl_OutStock : al) {
					
					if(ittl_OutStock.getQtyOUT()!=null ) {
						al2.add(ittl_OutStock);
					}
				}
			}
			//al=al2;
			System.out.println(al.toArray().toString());
/*/############################################
			BCStkRequestDAO dao = new BCStkRequestDAO();
			String hql = "FROM BCStkRequestBean where docNo='F1-CC-PR-5404-003' ";
			//ArrayList al = (ArrayList)dao.find(hql);
 			
			String a = getServlet().getServletContext().getRealPath("/");

			InputStream reportStream = new FileInputStream(a+"ireport\\rptMonthlyOutStock4.jasper");
			
			response.setContentType("application/pdf");
			
			JasperReport jasperReport = (JasperReport) JRLoader.loadObject(reportStream);
			
			HashMap<String,String> parameters = new HashMap<String,String>();
			JRDataSource datasource = new JRBeanCollectionDataSource(al);
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap(), datasource);
			
			JRPdfExporter pdfexport = new JRPdfExporter();
			
			// Setting the Values as parameter //
			pdfexport.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			// Setting the Destination File Name for the PDF (Extension Should be ".pdf") //
			pdfexport.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
			// Exporting the Report to PDF //
			pdfexport.exportReport();
			System.out.println("Report Generated");
###################################################*/		
			
			
			
			//InputStream reportStream = new FileInputStream("d://test.jasper");
			
			 // load report location
			//FileInputStream fis = new FileInputStream(a+"ireport\\test.jasper");
			//BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);
			// Bing the datasource with the collection
			//JRDataSource datasource = new JRBeanCollectionDataSource(al);
			// compile report
			//JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
			//JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap(), datasource);
			

			//InputStream reportStream = servlet.getServletConfig().getServletContext().getResourceAsStream("ireport\\test.jasper");
			//InputStream reportStream = new FileInputStream(a+"ireport\\test.jasper");//ReportReceiveMaterialAction.class.getResourceAsStream(a+"ireport\\test.jasper");			
			//new FileInputStream("d://test.jasper");
			
			// Bing the datasource with the collection
			//JRDataSource datasource = new JRBeanCollectionDataSource(al);
			// Print the jasper report
			//JasperPrint jasperPrint = JasperFillManager.fillReport(reportStream, parameters, datasource);
			//JasperPrintManager.printReport(print, true);
			// JasperRunManager.runReportToPdfStream(reportStream, getServlet(), parameters, connection);   
			//JasperViewer.viewReport(print);
			//JasperRunManager.runReportToPdfStream(reportStream, response.getOutputStream(), parameters, datasource);
			//ServletOutputStream servletOutputStream = response.getOutputStream();
			//JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parameters, new JRBeanCollectionDataSource(al));
			
			//response.setContentType("application/pdf");
			//servletOutputStream.flush();
			//servletOutputStream.close();
			
			//JRPdfExporter pdfexport = new JRPdfExporter();
			
			// Setting the Values as parameter //
			//pdfexport.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			// Setting the Destination File Name for the PDF (Extension Should be ".pdf") //
			//pdfexport.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,"D:/sample1.pdf");
			// Exporting the Report to PDF //
			//pdfexport.exportReport();
			//System.out.println("Report Generated");
			 
			 
			ReportReceiveMaterialForm rptForm = (ReportReceiveMaterialForm)form;
			String monthId = rptForm.getMonthId();
			String yearId = rptForm.getYearId();
			String[] selectedItems = rptForm.getSelectedItems();				
			String	process = rptForm.getProcess();
			
			String[] yearMonth = rptForm.getYearMonth().split("-");
			yearId = yearMonth[0];
			monthId = yearMonth[1];
			//################### new : start
			
			//################### new : end
			
			String nameOfReport = "";
			String timeToRequestReport = "";
			HashMap hashMap = new HashMap();
			if(process!=null && process.equalsIgnoreCase("new")) {
				Calendar cal = new GregorianCalendar(Integer.parseInt(yearId), Integer.parseInt(monthId)-1, 1);
				int  days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);     // 30  
				System.out.println("days = "+days);
				String sDate = yearId +"-" + monthId +"-1";
				String eDate = yearId +"-" + monthId +"-"+days;			
				System.out.println("sDate="+sDate);
				System.out.println("eDate="+eDate);
				timeToRequestReport = CommonUtils.now(); 
				new StockDAO().getMaterialOutStockReport(sDate, eDate, timeToRequestReport, "10");
							
				nameOfReport = "/ireport/receiveMaterial_department2.jasper";
			}else {
				nameOfReport = "/ireport/receiveMaterial_department21.jasper";
				nameOfReport = "/ireport/receiveMaterial_department23.jasper";
			}
			System.out.println("nameOfReport = "+nameOfReport);
			String dept = "";
			for(int i=0; i<selectedItems.length; i++) {
				dept = dept + "'"+selectedItems[i] +"',";
			}
			dept = " in ("+ dept.substring(0, dept.length()-1)+ ")";
			
			String monthStr[] = { "January","February", "March", "April", "May", "June", 
								  "July","August", "September", "October", "November", "December"};
			
			
			hashMap.put("monthId", monthId);
			System.out.println("monthId = "+monthId);
			hashMap.put("yearId", yearId);
			System.out.println("yearId = "+yearId);
			hashMap.put("dept", dept);
			System.out.println("dept = "+dept);
			hashMap.put("monthStr", monthStr[Integer.parseInt(monthId)-1]);
			System.out.println("monthStr = "+monthStr);
			hashMap.put("timeToRequestReport", timeToRequestReport);
			System.out.println("timeToRequestReport = "+timeToRequestReport);
			
			if(CommonUtils.runReportToPdf(response, getServlet(), hashMap, nameOfReport)==true) {
				System.out.println("run report to pdf: complete");
			}else {
				System.out.println("run Report to pdf: can't run report");
			}	
			
//			Connection connection;
//			ServletOutputStream servletOutputStream = response.getOutputStream();
//			
//			InputStream reportStream = getServlet().getServletConfig()
//							.getServletContext().getResourceAsStream("/ireport/receiveMaterial_department.jasper");
	//
//			
//			response.setContentType("application/pdf");
//			
//			//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//			Class.forName("net.sourceforge.jtds.jdbc.Driver");		
////			connection = DriverManager.getConnection("jdbc:odbc:ttl51","sa","admin123");
//			connection = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.1.2:1433/ttl51;user=sa;password=admin@123");
////			System.out.println("connect jTDS ok");
//			
//			JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, hashMap, connection);
//			connection.close();
//			servletOutputStream.flush();
//			servletOutputStream.close();	
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		
		return null;//mapping.getInputForward();
	}
	
	
	
	 	
}
